package com.ml.ws.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.ml.ws.config.TradingWebSocketChannelHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
/**
 * 
 * @author Mr.D
 * @Date 2020年6月29日
 */
@Component
@Slf4j
public class WebSocketClient{
  
	@Autowired
	TradingWebSocketChannelHandler tradingWebSocketChannelHandler;
	
	@Async
	public void start(int port) {
		EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        ChannelFuture f = null;
        try {
            //开启服务端
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(eventLoopGroup, workGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(tradingWebSocketChannelHandler);
            log.info("WS服务端(行情)开启等待客户端连接......Port-{}",port);
            f = serverBootstrap.bind(port).sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //退出程序
            eventLoopGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
            f.channel().close();
        }
	}


}
